import { getMenus } from '@/api/menu'
import { constantRouterMap } from '@/router'
/*import {reactive,ref} from "vue";*/

const menu = {
  state: {
    menus: [],
    // 第一次加载菜单时用到
    loadMenus: false,
    routers: constantRouterMap,
    addRouters: []
  },

  mutations: {
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_MENUS_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },

  actions: {
    // 获取信息
    GetMenus({ commit, state }) {
      return new Promise((resolve, reject) => {
        if(state.loadMenus && state.menus && state.menus.length > 0) {
          resolve(state.menus)
        } else {
          getMenus().then(res => {
            commit('SET_MENUS', res.data)
            commit('SET_LOAD_MENUS', true)
            resolve(res.data)
          }).catch(error => {
            reject(error)
          })
        }

      })
    },
    updateRouters({ commit, state }, routers) {
      return new Promise((resolve, reject) => {
        commit('SET_MENUS_ROUTERS', routers)
        resolve(true)
      })
    },
  }
}

export default menu
